package com.security.controller;

import com.security.bean.Blog;
import com.security.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: IndexController
 * @Author: ZhangYue26
 * @Description: 测试接口
 * @Date: 2021-01-19
 */
@Controller
public class IndexController {

    @Autowired
    private TestService testService;

    @RequestMapping("/")
    @ResponseBody
    public void root(HttpServletResponse response) {
        try {
            response.sendRedirect("index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/index")
    public void index(HttpServletResponse response) {
        try {
            response.sendRedirect("index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/login")
    public void  login(HttpServletResponse response) {
        try {
            response.sendRedirect("login.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/login-error")
    public Model loginError(Model model) {
        model.addAttribute("loginError.html", true);
        return model;
    }

    @ResponseBody
    @GetMapping("/401")
    public void accessDenied(HttpServletResponse response) {
        try {
            response.sendRedirect("401.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
      * @Description @PreAuthorize注解是在方法前进行权限验证，@PostAuthorize注解是在方法后进行权限验证
      * @author ZhangYue26
      * @date 2021/1/20
      * @param []
      * @return java.lang.String
      **/
    @PreAuthorize("hasAnyAuthority('USER')")
    @ResponseBody
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public String download(Blog blog) {
        return "下载成功";
    }

    @ResponseBody
    @RequestMapping(value = "getBlogs",method = RequestMethod.GET)
    public List getBlogs() {
        return testService.getBlogs();
    }

    @PreAuthorize("hasAnyAuthority('ADMIN')")
    @ResponseBody
    @RequestMapping(value = "/deleteBlogs/{id}",method = RequestMethod.GET)
    public void deleteBlogs(@PathVariable("id") Long id) {
        testService.deleteBlogs(id);
    }

}
